package com.hxexp.weixin.mvc.authenticode.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;

import com.hxexp.weixin.common.exception.APIException;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.common.math.RandomUtil;
import com.hxexp.weixin.constant.CacheName;
import com.hxexp.weixin.hpe.api.authenticode.AccountAuthenticodeAPI;
import com.hxexp.weixin.hpe.api.authenticode.model.AccountAuthenticodeParamBean;
import com.hxexp.weixin.hpe.api.authenticode.model.AccountAuthenticodeResultBean;
import com.hxexp.weixin.mvc.authenticode.service.AccountAuthenticodeService;

/**
 * 更新用户信息验证码服务实现类
 *
 * @author wang.bin
 * @author li.jiang
 */
@Service
public final class AccountAuthenticodeServiceImpl implements AccountAuthenticodeService {
    @Autowired
    private EhCacheCacheManager ehCacheManager;
    @Autowired
    private AccountAuthenticodeAPI accountAuthenticodeAPI;

    @Override
    public AccountAuthenticodeResultBean sendCaptcha(String mobile, String userId) throws ServiceException {
        AccountAuthenticodeParamBean accountAuthenticodeParam = new AccountAuthenticodeParamBean();
        AccountAuthenticodeResultBean accountAuthenticodeResult = new AccountAuthenticodeResultBean();

        // 生成验证码放入缓存
        String captcha = RandomUtil.getRandomNumber(6);
        Cache captchaCache = ehCacheManager.getCache(CacheName.HPE_ACCOUNTINFO_CAPTCHA);
        captchaCache.put(userId, captcha);
        // 设置请求参数
        accountAuthenticodeParam.setMobile(mobile);
        accountAuthenticodeParam.setCaptcha(captcha);
        accountAuthenticodeParam.setUserId(userId);

        try {
            accountAuthenticodeResult = accountAuthenticodeAPI.accountAuthenticode(accountAuthenticodeParam);
        } catch (APIException e) {
            throw new ServiceException(e);
        }
        return accountAuthenticodeResult;
    }

}
